import { onMounted, onUnmounted, type Ref } from "vue";

const useClickOutside = (elementRef: Ref<undefined | HTMLElement>, callback: (e: MouseEvent) => void) => {
  const handler = (e: MouseEvent) => {
    // elementRef 是容器元素  e 是点击元素
    if (elementRef.value && e.target) { 
      // 判断点击元素是否包含在容器里
      if (!elementRef.value.contains(e.target as HTMLElement)) {
        callback(e);
      }
    }
  };
  onMounted(() => {
    document.addEventListener('click', handler);
  })
  onUnmounted(() => {
    document.removeEventListener('click', handler);
  })
}

export default useClickOutside;